package com.wennimei.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.util.DataUtil;
import com.wennimei.util.FileProcessor;
import com.wennimei.util.FileUtil;
import com.wennimei.util.HttpUtil;

@Service
public class RailwayService {

    private static final Map<String, String> code = new HashMap<String, String>();

    @PostConstruct
    void init() {
        FileUtil.processFile(DataUtil.RAILWAY_CODE, new FileProcessor() {

            @Override
            public void process(String line) {
                String[] strs = line.split("\\|");
                code.put(strs[2], strs[3]);
            }
        });
    }

    public String get(String content) {
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Pattern p = Pattern.compile(".*(\\d{4}-\\d{2}-\\d{2}).*");
        Matcher m = p.matcher(content);
        while (m.matches()) {
            time = m.group(1);
            break;
        }
        content = content.replaceAll(time, "").trim();
        String f = content.substring(0, content.indexOf("到"));
        String t = content
                .substring(content.indexOf("到") + 1, content.length());

        String fromCode = null;
        String toCode = null;
        for (String s: code.keySet()) {
            if (s.equals(f))
                fromCode = code.get(s);
            else if (s.equals(t))
                toCode = code.get(s);

            if (null != fromCode && null != toCode)
                break;
        }

        if (null == fromCode || null == toCode)
            return "暂未查到该列车信息。可能由于起点到终点的列车暂未开通，请重试";
        String url = "http://dynamic.12306.cn/otsquery/query/queryRemanentTicketAction.do"
                + "?method=queryLeftTicket&orderRequest.train_date="
                + time
                + "&orderRequest.from_station_telecode="
                + fromCode
                + "&orderRequest.to_station_telecode="
                + toCode
                + "&orderRequest.train_no=&trainPassType=QB"
                + "&trainClass=QB%23D%23Z%23T%23K%23QT%23&includeStudent=00&seatTypeAndNum=&orderRequest.start_time_str=00%3A00--24%3A00";
        String res = HttpUtil.get(url);
        res = res.replaceAll("<[^>]+>", "").replaceAll("&nbsp;", "");
        Gson gson = new Gson();
        Map<String, Object> gs = gson.fromJson(res,
                new TypeToken<Map<String, Object>>() {}.getType());
        String data = (String) gs.get("datas");
        System.out.println(data);
        String[] datas = data.split(",");
        int length = datas.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0, j = length / 16; i < j; i++) {
            int base = i * 16;
            String checi = datas[base + 1];// 车次
            String from = datas[base + 2];// 出发
            String to = datas[base + 3];// 到达
            String ya = datas[base + 4];// 历时
            String yb = datas[base + 5];// 商务座
            String yc = datas[base + 6];// 特等座
            String yd = datas[base + 7];// 一等座
            String ye = datas[base + 8];// 二等座
            String yf = datas[base + 9];// 高级软卧
            String yg = datas[base + 10];// 软卧
            String yh = datas[base + 11];// 硬卧
            String yi = datas[base + 12];// 软座
            String yj = datas[base + 13];// 硬座
            String yk = datas[base + 14];// 无座
            String yl = datas[base + 15];// 其他
            sb.append("车次余票信息如下(" + (i + 1) + ")").append(checi).append(",")
                    .append(from).append(",").append(to).append(",")
                    .append("历时").append(ya).append(",");
            if (!"--".equals(yb) && !"无".equals(yb))
                sb.append("商务座:").append(yb).append("张,");
            if (!"--".equals(yc) && !"无".equals(yc))
                sb.append("特等座:").append(yc).append("张,");
            if (!"--".equals(yd) && !"无".equals(yd))
                sb.append("一等座:").append(yd).append("张,");
            if (!"--".equals(ye) && !"无".equals(ye))
                sb.append("二等座:").append(ye).append("张,");
            if (!"--".equals(yf) && !"无".equals(yf))
                sb.append("高级软卧:").append(yf).append("张,");
            if (!"--".equals(yg) && !"无".equals(yg))
                sb.append("软卧:").append(yg).append("张,");
            if (!"--".equals(yh) && !"无".equals(yh))
                sb.append("硬卧:").append(yh).append("张,");
            if (!"--".equals(yi) && !"无".equals(yi))
                sb.append("软座:").append(yi).append("张,");
            if (!"--".equals(yj) && !"无".equals(yj))
                sb.append("硬座:").append(yj).append("张,");
            if (!"--".equals(yk) && !"无".equals(yk))
                sb.append("无座:").append(yk).append("张,");
            if (!"--".equals(yl) && !"无".equals(yl))
                sb.append("其他:").append(yl).append("张\r\n");
        }
        return sb.toString();
    }
}
